package top.fengyulou.xiaofeng.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import top.fengyulou.xiaofeng.common.Jr;
import top.fengyulou.xiaofeng.common.MyUtils;
import top.fengyulou.xiaofeng.common.UserUtils;
import top.fengyulou.xiaofeng.domain.User;
import top.fengyulou.xiaofeng.dto.UserDto;
import top.fengyulou.xiaofeng.service.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author guochao
 * @Date 2022/2/10 20:56
 * @Version 1.0
 */
@Controller
public class CommonController {
    @Resource
    private UserService userService;

    /**
     * 用户修改密码
     */
    @RequestMapping("/user/child/update/password")
    public String userChildUpdatePassword() {
        return "user-update-password-child";
    }

    /**
     * 用户修改信息
     */
    @RequestMapping("/user/child/update/info")
    public String userChildUpdateInfo() {
        return "user-update-info-child";
    }

    //修改用户密码
    @RequestMapping("/user/ajax/update/password")
    @ResponseBody
    public Jr ajaxUpdatePassword(@RequestParam String pwdOld, @RequestParam String pwdNew, HttpServletRequest request) {
        JSONObject loginUser = UserUtils.getUser(request);
        if (!loginUser.getString("loginName").equals("admin")) {
            String userId = UserUtils.getUserId(request);
            UserDto byId = userService.getById(userId);
            pwdOld = MyUtils.getMd5(pwdOld);
            pwdNew = MyUtils.getMd5(pwdNew);
            if (!byId.getPassword().equals(pwdOld)) {
                return Jr.nom("原密码错误");
            } else if (pwdNew.equals(pwdOld)) {
                return Jr.yesm("修改成功");
            }
            //修改密码
            User user = new User();
            user.setId(userId);
            user.setPassword(pwdNew);
            user.setCurrentUserId(userId);
            userService.update(user);
        }
        return Jr.yesm("修改成功");
    }

    //修改用户信息
    @RequestMapping("/user/ajax/update/info")
    @ResponseBody
    public Jr ajaxUpdateInfo(User user, HttpServletRequest request) {
        JSONObject loginUser = UserUtils.getUser(request);
        if (!loginUser.getString("loginName").equals("admin")) {
            String userId = UserUtils.getUserId(request);
            user.setId(userId);
            user.setCurrentUserId(userId);
            userService.update(user);
        }
        return Jr.yesm("修改成功");
    }
}
